package org.lee.util;

import java.awt.*;
import java.util.List;

/**
 * @author jackielee
 * @version 1.0
 * @description StringUtil
 * @date 2021/5/12
 */
public class StringUtil {
  /**
   * 去除换行符
   *
   * @param str
   * @return
   */
  public static String trimLineBreak(String str) {
    if (isEmpty(str)) {
      return str;
    }
    return str.replace("\r", "").replace("\n", "");
  }

  public static boolean isEmpty(String str) {
    return str == null || str.trim().isEmpty();
  }

  public static boolean contains(String source, String str) {
    if (isEmpty(source) || isEmpty(str)) {
      return false;
    }
    return source.toLowerCase().contains(str.toLowerCase().trim());
  }

  public static boolean contains(List<String> source, String str) {
    for (String s : source) {
      if (contains(s, str)) {
        return true;
      }
    }
    return false;
  }

  public static Color toColor(String str) {
    if (isEmpty(str)) {
      return Color.WHITE;
    }
    str = str.trim();
    if (str.length() != 6) {
      return Color.WHITE;
    }
    int red = Integer.valueOf(str.substring(0, 2), 16);
    int green = Integer.valueOf(str.substring(2, 4), 16);
    int blue = Integer.valueOf(str.substring(4, 6), 16);
    return new Color(red, green, blue);
  }

  /**
   * 用0补齐左侧
   *
   * @param num 数值
   * @param len 字符串长度
   * @return 左补齐后字符串
   */
  public static String toPadString(int num, int len) {
    return toPadString(num, len, '0');
  }

  public static String toPadString(int num, int len, char ch) {
    StringBuilder sb = new StringBuilder();
    sb.append(num);
    for (int i = sb.length(); i < len; ++i) {
      sb.insert(0, ch);
    }
    return sb.toString();
  }

  /**
   * 字符串为null，则返回空字符串
   *
   * @param str
   * @return
   */
  public static String nullForEmpty(String str) {
    return str == null ? "" : str;
  }
}
